#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <sqlite3.h>
#include "Log.hpp"

namespace micromq
{

    class SqliteHelper
    {
    public:
        using sqlite_cb = int (*)(void*, int, char**,char**);
    public:
        SqliteHelper(const std::string& dbfile): _dbfile(dbfile), _handler(nullptr)
        {}

        bool open(int safeLevel = SQLITE_OPEN_FULLMUTEX)
        {
            int ret = sqlite3_open_v2(_dbfile.c_str(), &_handler, SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|safeLevel, nullptr);
            if(ret != SQLITE_OK)
            {
                logInfo("sqlite open failed: %s", sqlite3_errmsg(_handler));
                return false;
            }
            return true;
        }

        bool execute(const std::string& sql, sqlite_cb cb, void* arg)
        {
            int ret = sqlite3_exec(_handler, sql.c_str(), cb, arg, nullptr);
            if(ret != SQLITE_OK)
            {
                logInfo("sqlite execute failed: %s", sqlite3_errmsg(_handler));
                return false;
            }
            return true;
        }

        void close()
        {
            if(_handler) sqlite3_close_v2(_handler);
        }

        ~SqliteHelper()
        {}
    private:
        std::string _dbfile;
        sqlite3* _handler;
    };
}